<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>编辑商品属性</title>
  <link href="../../static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../../static/vendor/bootstrap-icons/bootstrap-icons.min.css" rel="stylesheet">
  <link href="../../static/css/vui365.min.css" rel="stylesheet">
</head>

<body>
  <div id="app">
    <form class="form-main form-horizontal" style="height:100vh" method="POST" ref="editForm">
      <div class="form-body container-fluid p-3"
        style="height:calc(100% - 45px); overflow-y: auto; overflow-x: hidden;">
        <table class="table table-sm table-bordered table-striped table-hover">
          <thead>
            <tr>
              <th style="width:4rem">启用</th>
              <th style="width:15rem">属性</th>
              <th>值</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,idx) of dataOfAttrs" :key="idx">
              <td><input type="checkbox" :value="item.value" :checked="item._isChecked" @click="onChecked($event,item)">
              </td>
              <td>{{item.text}}</td>
              <td><input :name="'val_'+item.value" class="form-control form-control-sm" type="search"
                  :value="item._inputValue" /></td>
            </tr>
          </tbody>
        </table>
        <!-- /.form-body -->
      </div>
      <div class="form-footer border-top pt-2 w-100 text-end">
        <button type="button" class="btn btn-secondary" @click.prevent="onCancelHandle()">取消</button>
        <cd-button class="btn btn-primary mx-2" @click="onSubmitHandle()">保存</cd-button>
    </form>
  </div>

  <script src="../../static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../../static/vendor/vue/vue.global.prod.min.js"></script>
  <script>
    // 全局配置
    this.vui365 = this.parent.vui365;

    // API接口配置
    const UrlCfg = {
      show: '/api/admin/ec-goods/{id}', // GET
      store: '/api/admin/ec-goods', // POST
      update: '/api/admin/ec-goods/{id}', // PUT
    }
    /**
     * 管理员组件
     * @description 管理员组件
     */
    const App = {
      // data 配置
      data() {
        return {
          id: 0,
          dataOfMain: {},
          dataOfAttrs: [],
          dataOfValues: [],
        };
      },
      // methods 配置
      methods: {
        // 初始化页面数据
        initData() {
          this.loadFormData();
        },
        // 初始化页面视图
        initView() {
          // 移除骨架屏
          document.querySelectorAll('.skeleton').forEach(el => {
            el.classList.remove("skeleton");
          })
        },
        async loadFormData() {
          vui365.globalApp.showLoading();
          const msgInfo = await vui365.stdAxios(UrlCfg.show.replace('{id}', this.id), { _mode: 'attrs' }, 'GET');
          vui365.globalApp.hideLoading();
          console.log("[加载表单数据] msgInfo=", this.id, msgInfo);
          if (msgInfo.status == 0) {
            alert(msgInfo.message);
            return;
          }
          this.dataOfMain = msgInfo.data.data;
          this.dataOfAttrs = msgInfo.data.attrs_data;
          this.dataOfValues = JSON.parse(msgInfo.data.data.attrs_data);
          this.dataOfAttrs.forEach(item => {
            item._isChecked = false;
            item._inputValue = '';
            for (let item2 of this.dataOfValues) {
              if (item2.id == item.value) {
                item._isChecked = true;
                item._inputValue = item2.value;
                break;
              }
            }
          })
          console.log('====', this.dataOfValues);
        },
        // 处理表单提交事件
        async onSubmitHandle() {
          let data = [], elForm = document.querySelector('form');
          elForm.querySelectorAll("input:checked").forEach(elCheckbox => {
            data.push({ id: elCheckbox.value, value: elForm.querySelector('input[name="val_' + elCheckbox.value + '"]').value.trim() })

          })
          let formData = { _mode: 'onefield', attrs_data: JSON.stringify(data) };
          let msgInfo = await vui365.stdAxios(UrlCfg.update.replace('{id}', this.id), formData, 'PUT');
          console.log("[提交表单] msgInfo=", msgInfo, formData);
          if (msgInfo.status == 0) {
            if (typeof msgInfo.message == "object") {
              let messageArr = [];
              for (let k in msgInfo.message) {
                msgInfo.message[k].forEach((text) => {
                  messageArr.push(text);
                });
              }
              msgInfo.message = messageArr.join("<br />");
            }
            vui365.BsDialog.alert(msgInfo.message);
            console.log('显示错误');
            return;
          }
          vui365.globalApp.closeFormDialog();
          vui365.globalApp.refreshDataTable()
        },
        // 处理表单取消事件
        onCancelHandle() {
          vui365.globalApp.closeFormDialog();
        },
        onChecked($event, item) {
          let isChecked = $event.target.checked;
          item._isChecked = isChecked; // 控件状态要和数据状态同步。
          for (let item2 of this.dataOfAttrs) {
            if (item2._level > item._level) {
              item2._isChecked = isChecked;
              console.log(item2);
              continue;
            }
            if (isChecked && (item2.value == item.pid)) {
              item2._isChecked = true;
              console.log('==', item2);
              continue;
            }
          }
        }
      },
      // created 生命周期方法
      created() {
        this.id = vui365.EsUtils.getQueryString("id", 0, window.location.search);
        this.initData();
      },
      // mounted 生命周期方法
      mounted() {
        this.initView();
      },
    };

    // 创建应用实例
    const app = Vue.createApp(App);
    //  注册组件
    app.component("UploadInput", vui365.getComponentOfUploadInput())
    app.component("SelectInput", vui365.getComponentOfSelectInput())
    app.component("CheckboxInput", vui365.getComponentOfCheckboxInput())
    app.component("RadioInput", vui365.getComponentOfRadioInput())
    app.component("CdButton", vui365.getComponentOfCdButton())
    // 加载根元素
    app.mount('#app');
  </script>

</body>

</html>